package com.zjitc.service.impl;

import com.zjitc.dao.UserDao;
import com.zjitc.model.User;
import com.zjitc.service.UserService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/9 14:58
 * @description:
 */
@Service
public class UserServiceImpl implements UserService{

  @Autowired
  private UserDao userDao;

  @Override
  public int insertUser() {

    List<User> userList=new ArrayList<>();

    for (int i=0;i<150000;i++){
      User user=new User();
      int randNumber =new Random().nextInt(100-0+1)+0;
      user.setAge(randNumber);
      if (i%2==0){
        user.setSex("m");
      }else {
        user.setSex("w");
      }
      userList.add(user);
    }

    int count=userDao.addUsers(userList);
    return count;
  }

  @Override
  public List<User> findByDataBase() {
    return userDao.findByDataBase();
  }

  @Override
  public List<User> findUserAll() {
    Jedis jedis=new Jedis("localhost");
    List<User> users=userDao.findUserAll();
    final String KEY_SEX_W="KEY_SEX_W";
    final String KEY_AGE_LARGER_45="KEY_AGE_LARGER_45";

    for (User user:users){
      if (user.getAge() >=45){

      }
    }

    users.forEach((item)->{

      HashMap<String,String> map = new HashMap<>();
      map.put("age", String.valueOf(item.getAge()));
      map.put("sex", item.getSex());
      jedis.hmset(String.valueOf(item.getId()),map);
      if (item.getAge()>=45){
        jedis.sadd(KEY_AGE_LARGER_45, String.valueOf(item.getId()));
      }
      if (item.getSex().equals("w")){
        jedis.sadd(KEY_SEX_W, String.valueOf(item.getId()));
      }
    });

    Set<String> sinter= jedis.sinter(KEY_SEX_W,KEY_AGE_LARGER_45);
    System.out.println(sinter);
    Set<String> sdiff=jedis.sdiff(KEY_SEX_W,KEY_AGE_LARGER_45);
    System.out.println(sdiff);
    Set<String> sunion=jedis.sunion(KEY_SEX_W,KEY_AGE_LARGER_45);
    System.out.println(sunion);

    sinter.forEach(item->{
      Map<String, String> stringStringMap = jedis.hgetAll(item);
      System.out.println(stringStringMap);
    });
    return users;
  }
}
